package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 设置过滤器
 * 检查用户是否登录
 * 拦截没有登录的请球
 */

@Slf4j
@WebFilter("/*")
public class CheckLoginFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取uri路径
        String requestURI = request.getRequestURI();
        //创建需要放行的页面静态资源
        String[] uris ={
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/user/sendMsg",   //移动端发送验证码
                "/user/login"      //异动端登录
        };
        //判断获取的路径需不需要放行
        boolean flag = check(uris, requestURI);
        if (flag){
            //放行
            filterChain.doFilter(request,response);
            return;
        }

        //2.获取session里面的数据, 用于员工登录
        Long employee = (Long) request.getSession().getAttribute("employee");
        //把这个值设置到当前线程中去
        BaseContext.set(employee);
        //判断登录状态,如果已经登录就放行
        if (employee!=null){
            //放行
            filterChain.doFilter(request,response);
            return;
        }

        //2.获取session里面的数据,用于用户登录
        Long userId = (Long) request.getSession().getAttribute("user");
        //把这个值设置到当前线程中去
        BaseContext.set(userId);
        //判断登录状态,如果已经登录就放行
        if (userId!=null){
            //放行
            filterChain.doFilter(request,response);
            return;
        }
        //表示用户未登录,code=0 msg=NOTLOGIN
        String notlogin = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(notlogin);
    }

    /**
     * 匹配路径,检查是否放行
     * @param uris
     * @param requestURI
     * @return
     */

    private boolean check(String[] uris, String requestURI) {
        for (String uri : uris) {
            boolean match = PATH_MATCHER.match(uri, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
